package com.wq.code;

/**
 * @Author: wangqiang20995
 * @Date:2019/9/28
 * @Description:
 * @Resource:
 */
public class HexStringUtils {

    private static final String STORE_SERIAL = "0123456789ABCDEF";

    public static byte[] hexString2Bytes(String hex) {
        if (hex == null || "".equals(hex.trim())) {
            return null;
        }

        if ((hex.length() & 1) == 1) {
            throw new IllegalArgumentException("hex string length illegal");
        }

        byte[] data = new byte[hex.length() >> 1];

        char[] codes = hex.toCharArray();
        for (int i = 0; i < hex.length(); i = i + 2) {
            int pre = STORE_SERIAL.indexOf(codes[i]);
            int sub = STORE_SERIAL.indexOf(codes[i + 1]);

            data[i >> 1] = (byte) ((pre << 4) + sub);
        }

        return data;
    }

    public static void main(String[] args) {
        for (byte b : hexString2Bytes("12B3F9")) {
            System.out.printf("%d\t", b);
        }
    }
}
